package cn.mcch.investigator.presenter.impl;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.mcch.investigator.R;
import cn.mcch.investigator.adapter.base.CommonAdapter;
import cn.mcch.investigator.adapter.base.CommonExpandableListAdapter;
import cn.mcch.investigator.adapter.base.ViewHolder;
import cn.mcch.investigator.application.InvestigatorApplication;
import cn.mcch.investigator.customview.StateEditText;
import cn.mcch.investigator.customview.expandablelayout.ExpandableLinearLayout;
import cn.mcch.investigator.customview.pulltorefresh.PullToRefreshLayout;
import cn.mcch.investigator.listener.OnResponseListener;
import cn.mcch.investigator.model.bean.CancelRescueBean;
import cn.mcch.investigator.model.bean.MyTaskBean;
import cn.mcch.investigator.model.bean.Order;
import cn.mcch.investigator.model.impl.MyTaskModelImpl;
import cn.mcch.investigator.observer.InvestigatorObserverable;
import cn.mcch.investigator.presenter.BasePresenter;
import cn.mcch.investigator.presenter.IMyTaskPresenter;
import cn.mcch.investigator.utils.ConstantUtil;
import cn.mcch.investigator.utils.JsonUtils;
import cn.mcch.investigator.utils.L;
import cn.mcch.investigator.viewdelegate.impl.MyTaskViewDelegateImpl;

/**
 * Created by Administrator on 2016/12/17.
 */
public class MyTaskPresenterImpl extends BasePresenter<MyTaskViewDelegateImpl, MyTaskModelImpl> implements IMyTaskPresenter {

    private CommonAdapter<Order> adapter;

    private SparseArray<String> editTextSparseArray = new SparseArray<>();
    private SparseArray<Integer> rbSparseArray = new SparseArray<>();

    @Override
    public Class<MyTaskViewDelegateImpl> getViewDelegateClass() {
        return MyTaskViewDelegateImpl.class;
    }

    @Override
    public Class<MyTaskModelImpl> getModelClass() {
        return MyTaskModelImpl.class;
    }


    public MyTaskBean myTaskBean;

    public int page;

    @Override
    public void viewBindData(MyTaskViewDelegateImpl viewDelegate, String json) {
        myTaskBean = JsonUtils.fromJsonToObject(json, MyTaskBean.class);
        for (int i = 0; i < myTaskBean.list.size(); i++) {
            rbSparseArray.put(i, R.id.rb_jckc);
        }
        adapter = new CommonAdapter<Order>(InvestigatorApplication.getInstance(), R.layout.list_item_my_task, myTaskBean.list) {
            @Override
            protected void convert(ViewHolder viewHolder, Order item, int position) {
                ExpandableLinearLayout ell = viewHolder.getView(R.id.ell_list_item);
                StateEditText stateEditText = viewHolder.getView(R.id.se_cancel_reason);
                stateEditText.setTag(position);
                stateEditText.addTextChangedListener(new MyTextWatcher(position, stateEditText));
                viewHolder.setText(R.id.se_cancel_reason, editTextSparseArray.get(position));
                ImageView arrow = viewHolder.getView(R.id.iv_arrow);
                viewHolder.setOnClickListener(R.id.iv_arrow, new MyOnClickListener(arrow, ell, item));
                viewHolder.setOnClickListener(R.id.sb_yes_cancel_rescue, new CancelRescueOnClickListener(item, viewHolder));
                if (item.isExpand) {
                    ell.expand(false);
                } else {
                    ell.collapse(false);
                }
                ((RadioGroup) viewHolder.getView(R.id.rg_cancel_reason)).setOnCheckedChangeListener(null);
                ((RadioButton) viewHolder.getView(rbSparseArray.get(position))).setChecked(true);
                ((RadioGroup) viewHolder.getView(R.id.rg_cancel_reason)).setOnCheckedChangeListener(new MyOnCheckedChangeListener(position));
                viewHolder.setVisible(R.id.ll_cancel_rescue, item.cancel == 1 ? true : false);
                viewHolder.setImageResource(R.id.iv_arrow, item.isExpand ? R.drawable.arrow_up : R.drawable.arrow_down);
                viewHolder.setText(R.id.tv_order_no, item.sn).setText(R.id.tv_customer_car, item.no).setText(R.id.tv_order_attr, item.attr)
                        .setText(R.id.tv_order_type, item.type)
                        .setText(R.id.tv_customer_car_type, item.car)
                        .setText(R.id.tv_customer, item.name)
                        .setText(R.id.tv_customer_phone, item.tel)
                        .setText(R.id.tv_order_area, item.area);
                // 推修单位
                viewHolder.setVisible(R.id.tv_order_txdw, TextUtils.isEmpty(item.garage_name) ? false : true);
                viewHolder.setText(R.id.tv_order_txdw, item.garage_name);
                // 救援公司名称
                viewHolder.setVisible(R.id.tv_rescue_company, TextUtils.isEmpty(item.com_name) ? false : true);
                viewHolder.setText(R.id.tv_rescue_company, item.com_name);
                // 救援人员
                viewHolder.setVisible(R.id.tv_driver, TextUtils.isEmpty(item.driver_name) ? false : true);
                viewHolder.setText(R.id.tv_driver, item.driver_name);
                // 救援人员联系方式
                viewHolder.setVisible(R.id.tv_driver_phone, TextUtils.isEmpty(item.driver_tel) ? false : true);
                viewHolder.setText(R.id.tv_driver_phone, item.driver_tel);
                // 救援人员车牌号
                viewHolder.setVisible(R.id.tv_driver_car, TextUtils.isEmpty(item.driver_no) ? false : true);
                viewHolder.setText(R.id.tv_driver_car, item.driver_no);
                // 救援人员车型
                viewHolder.setVisible(R.id.tv_driver_car_type, TextUtils.isEmpty(item.driver_type) ? false : true);
                viewHolder.setText(R.id.tv_driver_car_type, item.driver_type);
                // 录入时间
                viewHolder.setVisible(R.id.tv_lrsj, TextUtils.isEmpty(item.addtime) ? false : true);
                viewHolder.setText(R.id.tv_lrsj, item.addtime);
                // 推修时间
                viewHolder.setVisible(R.id.tv_txsj, TextUtils.isEmpty(item.recommend_time) ? false : true);
                viewHolder.setText(R.id.tv_txsj, item.recommend_time);
                // 案件状态
                viewHolder.setVisible(R.id.tv_order_status, TextUtils.isEmpty(item.status) ? false : true);
                viewHolder.setText(R.id.tv_order_status, item.status);

            }
        };
        mViewDelegate.setAdapterViewAdapter(R.id.plv_my_task, adapter);


        // 判断是否可以加载更多
        isNoMoreData();

    }

    public void setRefreshResult(int result) {
        ((PullToRefreshLayout) mViewDelegate.findViewById(R.id.prl_my_task)).refreshFinish(result);
    }

    public void setLoadMoreResult(boolean result) {
        ((PullToRefreshLayout) mViewDelegate.findViewById(R.id.prl_my_task)).loadFinish(result);
    }


    public void setMoreData(MyTaskBean bean) {
        for (int i = myTaskBean.list.size(); i < myTaskBean.list.size() + bean.list.size(); i++) {
            rbSparseArray.put(i, R.id.rb_jckc);
        }
        myTaskBean.list.addAll(bean.list);
        adapter.notifyDataSetChanged();
    }

    public void setRefreshData(MyTaskBean bean) {

        myTaskBean.allpage = bean.allpage;
        myTaskBean.list.clear();
        myTaskBean.list.addAll(bean.list);

        rbSparseArray.clear();
        for (int i = 0; i < myTaskBean.list.size(); i++) {
            rbSparseArray.put(i, R.id.rb_jckc);
        }
        adapter.notifyDataSetChanged();
    }


    public void getMoreData(int id, OnResponseListener listener) {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("user_id", InvestigatorApplication.getInstance().getUserBeanbean().user_id);
        params.put("page", String.valueOf(page));
        params.put("keyw", mViewDelegate.getText(R.id.se_find_key));
        params.put("s_time", mViewDelegate.getText(R.id.sb_find_start));
        params.put("e_time", mViewDelegate.getText(R.id.sb_find_end));
        mModel.request(id, ConstantUtil.ACT_ORDER_LIST, params, listener);
    }

    public void isNoMoreData() {
        ((PullToRefreshLayout) mViewDelegate.findViewById(R.id.prl_my_task)).setLoadNoData(page == myTaskBean.allpage);
    }

    public void setNoMoreData(Boolean result) {
        ((PullToRefreshLayout) mViewDelegate.findViewById(R.id.prl_my_task)).setLoadNoData(result);
    }

    @Override
    public void cancelRescue(int id, String order_id, String reason, String other, OnResponseListener listener) {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("user_id", InvestigatorApplication.getInstance().getUserBeanbean().user_id);
        params.put("order_id", order_id);
        params.put("reason", reason);
        params.put("other", other);
        mModel.cancelRescue(id, ConstantUtil.ACT_ORDER_CANCEL, params, listener);
    }

    public void setDate(int selectDate, int year, int monthOfYear, int dayOfMonth) {

        mViewDelegate.setText(selectDate == 1 ? R.id.sb_find_start : R.id.sb_find_end, year + "-"
                + ((monthOfYear + 1) > 10 ? (monthOfYear + 1) : "0" + (monthOfYear + 1)) + "-"
                + (dayOfMonth > 10 ? dayOfMonth : "0" + dayOfMonth));
    }

    public void clearData() {
        myTaskBean.list.clear();
        adapter.notifyDataSetChanged();
    }

    private class MyOnClickListener implements View.OnClickListener {
        private ImageView arrow;
        private ExpandableLinearLayout ell;
        private Order item;

        public MyOnClickListener(ImageView arrow, ExpandableLinearLayout ell, Order item) {
            this.arrow = arrow;
            this.ell = ell;
            this.item = item;
        }


        @Override
        public void onClick(View v) {
            item.isExpand = !item.isExpand;
            arrow.setImageResource(ell.isExpanded() ? R.drawable.arrow_down : R.drawable.arrow_up);
            ell.toggle();
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private int position;
        private EditText editText;

        public MyTextWatcher(int position, EditText editText) {
            this.position = position;
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            Integer tag = (Integer) editText.getTag();
            editTextSparseArray.put(tag, s.toString());
        }
    }

    private class CancelRescueOnClickListener implements View.OnClickListener {

        private Order item;
        private ViewHolder holder;

        public CancelRescueOnClickListener(Order item, ViewHolder holder) {
            this.item = item;
            this.holder = holder;
        }

        @Override
        public void onClick(View v) {
            CancelRescueBean cancelRescueBean = new CancelRescueBean();
            cancelRescueBean.order_id = item.order_id;
            RadioGroup radioGroup = holder.getView(R.id.rg_cancel_reason);
            cancelRescueBean.reason = radioGroup.getCheckedRadioButtonId() == R.id.rb_jckc ? "1" : "2";
            cancelRescueBean.other = holder.getText(R.id.se_cancel_reason);
            InvestigatorObserverable.notifyObservers(400, cancelRescueBean);
        }
    }

    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        private int position;

        public MyOnCheckedChangeListener(int position) {
            this.position = position;
        }

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            rbSparseArray.put(position, checkedId);
        }
    }

}
